package com.example.demo.algorithm.consistent_hash;

import java.util.*;

/**
 * 定义一个节点类，实现数据节点的功能
 */
public class Node {
    private static final int VIRTUAL_NODE_NO_PRE_NODE = 200;
    private final String ip;
    private final List<Integer> virtualNodeHashes = new ArrayList<>(VIRTUAL_NODE_NO_PRE_NODE);
    private final Map<Object,Object> cacheMap = new HashMap<>();

    public Node(String ip){
        Objects.requireNonNull(ip);
        this.ip = ip;
        initVirtualNodes();
    }

    private void initVirtualNodes(){
        String virtualNodeKey;
        for (int i = 1; i < VIRTUAL_NODE_NO_PRE_NODE; i++) {
            virtualNodeKey = this.ip + "#" + i;
            virtualNodeHashes.add(Objects.hashCode(virtualNodeKey));
        }
    }

    public void addCacheItem(Object key,Object value){
        cacheMap.put(key,value);
    }

    public Object getCacheItem(Object key){
        return cacheMap.get(key);
    }

    public void removeCacheItem(Object key){
        cacheMap.remove(key);
    }

    public List<Integer> getVirtualNodeHashes(){
        return virtualNodeHashes;
    }

    public String getIp(){
        return ip;
    }
}
